package per.jdz.retryer.strategy;

import java.util.concurrent.TimeUnit;

/**
 * 指数退避重试策略
 */
public class ExponentialRetryerStrategy extends AbstractRetryerStrategy{

    public int baseCount = 1;

    public ExponentialRetryerStrategy(int count, long time, TimeUnit timeUnit) {
        super(count, time, timeUnit);
    }

    @Override
    boolean exec() {
        while (count >= baseCount) {
            try {
                long waitTime = (long) (time * Math.pow(2, baseCount++ - 1));
                timeUnit.sleep(waitTime);
                return true;
            } catch (InterruptedException e) {
                // 在等待期间被中断，抛出异常
                Thread.currentThread().interrupt();
                throw new RuntimeException("Retryer interrupted", e);
            }
        }
        return false;
    }

    @Override
    public void reset() {
        baseCount = 1;
    }
    
}
